package com.bookmanager.www.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bookmanager.www.common.Constants.PreferentialConstant;
import com.bookmanager.www.common.DTO.UserDTO;
import com.bookmanager.www.common.utils.*;
import com.bookmanager.www.entity.FlBookOrder;
import com.bookmanager.www.entity.FlOauth2;
import com.bookmanager.www.entity.FlUser;
import com.bookmanager.www.entity.LoginDetail;
import com.bookmanager.www.mapper.FlUserMapper;
import com.bookmanager.www.service.FlBookorderService;
import com.bookmanager.www.service.FlUserService;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.PrecisionMetric;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 风离
 * @since 2021-09-17
 */
@RestController
@RequestMapping("/fl-user")
@Slf4j
@Api(tags = "用户管理")

public class FlUserController {
    @Resource
    FlUserService flUserService;

    @Resource
    FlUserMapper flUserMapper;
    @Resource
    FlBookorderService flBookorderService;

    @GetMapping("/getUserPayPassword")
    @ApiOperation(value = "获取用户支付密码")
   public Result getUserPayPassword(){
        String userId =ShiroUtils.getUserId();
        //这里判断是否设置了支付密码
        String password = flUserMapper.selectUserPayPasswordByUserId(userId);
        if(password==null||password.equals(""))
        {
            return Result.fail("未设置支付密码！！","");
        }
        return Result.succ("操作成功！",password);
    }

    @GetMapping("/getUserByToken")
    @ApiOperation(value = "通过token获取用户信息 无需传参",notes = "")
    public Result getUserByToken()
    {
        String userId = ShiroUtils.getUserId();
        return Result.succ("操作成功！",flUserMapper.selectUserById(userId));
    }



    @PostMapping("/createPayPassword")
    @ApiOperation(value = "创建用户支付密码")
    public Result createPayPassword(@RequestParam("payPassword")String payPassword)
    {
        log.info("前端传入的支付密码是："+payPassword);
        //这里进行支付密码校验
        if(payPassword.length()!=6)
        {
            return Result.fail("创建的支付密码长度有问题！！！","");
        }

        String userId = ShiroUtils.getUserId();
        //如果该用户已有支付密码会创建失败！！(防止异常调用接口)
        String test = flUserMapper.selectUserPayPasswordByUserId(userId);
        if(test!=null)
        {
            return Result.fail("创建支付密码失败，用户已有支付密码！！！","");
        }

        String encryptPassword = CommonsUtils.encryptPassword(payPassword,"fl1906");
        LocalDateTime createTime = LocalDateTime.now();
        int insertUserPayPassword = flUserMapper.insertUserPayPassword(userId,encryptPassword,createTime);
        if(insertUserPayPassword!=0)
        {
            return Result.succ("支付密码创建成功！！","");
        }
        return Result.fail("创建支付密码失败！！","其他错误导致插入数据库失败！！");
    }


    @PostMapping("/updatePayPassword")
    @ApiOperation(value = "修改支付密码")
    public Result updatePayPassword(@RequestParam("newPayPassword")String payPassword)
    {
        String encryptPassword = CommonsUtils.encryptPassword(payPassword,"fl1906");
        String userId = ShiroUtils.getUserId();
        int updatePayPassword = flUserMapper.updateUserPayPassword(userId,encryptPassword);
        if(updatePayPassword!=0)
        {
            return Result.succ("支付密码修改成功！！","");
        }
        return Result.fail("修改支付密码失败！！","其他错误导致更新数据库失败！！");
    }

    @DeleteMapping("/revoke/{source}")
    @ApiOperation(value = "用户与第三方解绑")
    /**
     * 每个用户对应第三方平台应该是一对一的 所以uuid 可以通过userId+source 获得
     */
    public Result revokeAuth(@PathVariable("source") String source) throws IOException {
        String userId =ShiroUtils.getUserId();
        String uuid = flUserMapper.selectUUIDByuserIdAndSource(userId,source);
        if(uuid!=null)
        {
            //删除该字段即可解绑
            int deleted  = flUserMapper.deleteUUIDbyUUIDAndSource(uuid,source);
            if(deleted!=0)
            {
                return Result.succ("解绑第三方"+source+"成功！！","");
            }else {
                return Result.fail("解绑失败！！","");
            }
        }

        return Result.fail("找不到第三方账号的uuid！！！！！","");
    }

    @GetMapping("/searchUsersOAuth2")
    @ResponseBody
    @ApiOperation(value = "查询用户所绑定的第三方账号")
    Result searchUsersOAuth2()
    {
        String userId = ShiroUtils.getUserId();
        List<FlOauth2> flOauth2List  = flUserMapper.selectUsersOAuth2(userId);
        if(flOauth2List.size()!=0)
        {
            return Result.succ("查询成功",flOauth2List);
        }
        return Result.fail("该用户尚未绑定第三方账号","");
    }

    @PostMapping("/createBalanceRecharge")
    @ApiOperation(value = "创建余额充值订单")
    Result createBalanceRecharge(@RequestParam("userId")String userId,@RequestParam("amount")String amount)
    {
        //这里判断是否设置了支付密码
        String password = flUserMapper.selectUserPayPasswordByUserId(userId);
        if(password==null||password.equals(""))
        {
            return Result.fail("未设置支付密码！！","");
        }





        System.out.println("传入的金额为"+amount);
        Double amount2 = Double.parseDouble(amount);
        if(amount2!=null)
        {
            System.out.println("转换为double之后金额为"+amount2);
            FlBookOrder order = flBookorderService.createOrder(userId, amount2, "余额充值");
            if(order!=null)
            {
                return Result.succ("创建余额支付订单成功",order.getOrderId());
            }

        }
        return Result.fail("创建余额支付订单失败","");
    }

    @PostMapping("/changeAvatarByQQ")
    @ApiOperation(value = "通过qq修改头像")
    Result changeAvatarByQQ(@RequestParam("userId")String userId,@RequestParam("QQ")String qq)
    {
        log.info("前端传给我的用户id"+userId);
        log.info("不需要前端传用户id获取到的用户id"+ShiroUtils.getUserId());
        String avatar = "https://q4.qlogo.cn/g?b=qq&nk="+qq+"&s=640";
        int updateAvatar = flUserMapper.updateAvatarByUserId(userId, avatar);
        if(updateAvatar!=0)
        {
            return Result.succ("修改头像成功",avatar);
        }
        return Result.fail("数据库更新失败!!","");
    }

    @PostMapping("/changeAccountBalance")
    @ApiOperation(value = "修改用户余额",notes = "传入用户id 和修改后的余额即可")
    Result changeAccountBalance(@RequestParam("userId")String userId,@RequestParam("newAccountBalance")String balance)
    {
          BigDecimal newBalance = new BigDecimal(balance);

          BigDecimal accountBalance = flUserService.changeAccountBalanceByUserId(userId,newBalance);

          if(accountBalance!=null)
          {
              return Result.succ("修改用户余额成功 该用户目前为普通用户！！",accountBalance);
          }

//          String superLevel = "5000";
//
//          String normal = "500";
//          if(accountBalance!=null)
//          {
//              if(accountBalance.compareTo(new BigDecimal(superLevel))==1)
//              {
//                  //如果用户余额>5000 给用户升级为超级会员
//                  int update = flUserMapper.upLevel(userId,2);
//                  if(update!=0)
//                  {
//                      return Result.succ("修改用户余额成功 该用户目前为超级会员！！",flUserMapper.selectAccountBalanceByUserId(userId));
//                  }
//              }else if(accountBalance.compareTo(new BigDecimal(normal))==1)
//              {
//                  //如果用户余额>500 给用户升级为普通会员
//                  int update = flUserMapper.upLevel(userId,1);
//                  if(update!=0)
//                  {
//                      return Result.succ("修改用户余额成功 该用户目前为普通会员！！",flUserMapper.selectAccountBalanceByUserId(userId));
//                  }
//              }else {
//                  return Result.succ("修改用户余额成功 该用户目前为普通用户！！",flUserMapper.selectAccountBalanceByUserId(userId));
//              }
//          }

        return Result.fail("修改余额失败！","");
    }


    @PostMapping("checkAccountLevel")
    @ApiOperation(value = "查看用户等级",notes = "传入用户id即可  0 普通用户 1 普通会员 2 超级会员")
    Result checkAccountLevel(@RequestParam("userId")String userId)
    {
         int userLevel = flUserMapper.selectAccountLevelByUserId(userId);
//         System.out.println("转换为百分比为"+userLevel/8.0);

        //百分制
         return  Result.succ("查看用户等级",new BigDecimal((userLevel/8.0)*100));
    }

    @PostMapping("/unBingPhoneNum")
    @ApiOperation(value = "解绑手机号",notes = "传入用户id即可")
    Result unBingPhoneNum(@RequestParam("userId")String userId)
    {
        int update = flUserMapper.unBindPhoneNum(userId);
        if(update!=0)
        {
            return Result.succ("解绑成功！","");
        }

        return Result.fail("解绑失败","数据库没有更新 即原本该手机号就不存在!");
    }


    @PostMapping("/unBindEmail")
    @ApiOperation(value = "解绑邮箱号",notes = "传入用户id")
    /**
     * 解绑邮箱步骤： 发送邮箱验证码 确认用户身份 然后解绑即可
     */
    Result unBindEmail(@RequestParam("userId")String userId)
    {
        int update = flUserMapper.unBindEmail(userId);
        if(update!=0)
        {
            return Result.succ("解绑成功！","");
        }


        return Result.fail("解绑失败","数据库没有更新 即原本该邮箱号就不存在!");
    }

    @PostMapping("/changeUserPhoneNum")
    @ApiOperation(value = "修改/新增用户手机号",notes = "传入用户id 和手机号")
    Result changeUserPhoneNum(@RequestParam("userId")String userId,@RequestParam("phoneNum")String phoneNum)
    {
        // 首先判断该手机号是否存在  前端做
       int updated = flUserMapper.changeUserPhoneNum(userId,phoneNum);
       if(updated!=0)
       {
           return Result.succ("修改成功","修改之后的手机号为"+phoneNum);
       }
        return Result.fail("修改失败","未知原因");
    }

    @PostMapping("/changeUserEmail")
    @ApiOperation(value = "修改/新增用户邮箱",notes = "传入用户id 和邮箱号")
    Result changeUserEmail(@RequestParam("userId")String userId,@RequestParam("email")String email)
    {
        int updated = flUserMapper.changeUserEmail(userId,email);
        if(updated!=0)
        {
            return Result.succ("修改成功","修改之后的邮箱号为"+email);
        }

        return Result.fail("修改失败","未知原因");
    }


    @PostMapping("/changeUserSex")
    @ApiOperation(value ="修改用户性别",notes = "传入修改后的用户性别和用户id")
    Result changeUserSex(@RequestParam("userId")String userId,@RequestParam("sex")Integer sex)
    {
        System.out.println("传入的性别是"+sex);
        if (sex!=1&&sex!=0)
        {
          return Result.fail("传入的性别不男不女~~","");
        }
        int updated = flUserMapper.changeUserSex(userId,sex);
        if(updated!=0)
        {
            return Result.succ("修改成功","用户修改后的性别"+(sex==1?"男":"女"));
        }
        return Result.fail("修改失败","未知原因");

    }

    @PostMapping("/changeUserDesc")
    @ApiOperation(value = "修改用户个签",notes = "传用户id和个签内容")
    Result changeUserDesc(@RequestParam("userId")String userId,@RequestParam("desc")String desc)
    {
        System.out.println("传入的用户id是"+userId+"=====desc："+desc);
        int updated=flUserMapper.changeUserDesc(userId,desc);
        if(updated!=0)
        {
            return Result.succ("修改成功",desc);
        }

        return Result.fail("修改失败","未知原因");
    }


    @PostMapping("/changeUsername")
    @ApiOperation(value ="修改用户名",notes = "传入oldUsername  newUsername")
    Result changeUsername(@RequestParam("newUsername")String newUsername,@RequestParam("oldUsername")String oldUsername)
    {
        int update = flUserMapper.changeUsernameByOldUsername(oldUsername,newUsername);
        if(update!=0)
        {
            return Result.succ("修改用户名成功！","");
        }
        return Result.fail("修改失败","");
    }

    @PostMapping("/findPasswordByQuestion")
    @ApiOperation(value ="找回密码1",notes = "传入answer 和用户名")
    Result findPasswordByQuestion(@RequestParam("answer") String answer,@RequestParam("username")String username)
    {
           FlUser flUser= flUserMapper.selectUserByUsername(username);
           String answers = flUser.getAnswer();
           if(answer.equals(answers))
           {
               return Result.succ("问题回答正确！","可以修改密码");
           }
           return Result.fail("问题回答错误！","不可以修改密码");
    }
    @PostMapping("/changePasswordByUsername")
    @ApiOperation(value ="找回密码2",notes = "传入用户名 新密码")
    Result changePasswordByUsername(@RequestParam("username") String username,@RequestParam("password") String password)
    {

        FlUser flUser =flUserMapper.selectUserByUsername(username);
        //String encryptedPassword= CommonsUtils.encryptPassword(password, "fl1906");
        if(flUser.getPassword().equals(CommonsUtils.encryptPassword(password, "fl1906")))
        {
            return Result.fail("修改密码失败","老密码不能与新密码相同！");
        }
        int update = flUserMapper.changePasswordByUsername(username,CommonsUtils.encryptPassword(password, "fl1906"));
        if(update!=0)
        {
            return Result.succ("修改密码成功！","");
        }

        return Result.fail("修改密码失败","未知错误~~");
    }

    @PostMapping("/changePasswordByOldPassword")
    @ApiOperation(value = "通过老密改密码",notes = "传入用户名 老密 新密 改密码之后可以进行登出操作 让用户重新登陆")
    Result changePasswordByOldPassword(@RequestParam("username")String username,
                                       @RequestParam("oldPassword")String oldPassword,
                                       @RequestParam("newPassword")String newPassword)
    {
        FlUser flUser=flUserMapper.selectUserByUsername(username);
        System.out.println("传入加密后的老密是："+CommonsUtils.encryptPassword(oldPassword, "fl1906"));
        System.out.println("数据库中密码    是："+flUser.getPassword());
        if(!CommonsUtils.encryptPassword(oldPassword, "fl1906").equals(flUser.getPassword()))
        {
            return Result.fail("修改密码失败","老密码错误！！");
        }else {
            int updatePassword = flUserMapper.changePasswordByOldPassword(CommonsUtils.encryptPassword(oldPassword, "fl1906"),
                    CommonsUtils.encryptPassword(newPassword, "fl1906"));
            if(updatePassword!=0)
            {
                return Result.succ("修改密码成功！！","");
            }
        }

        return Result.fail("修改密码失败","未知错误！");
    }

    @PostMapping("/changeUserAvatar")
    @ApiOperation(value ="修改用户头像",notes = "传入用户上传的头像文件")
    Result changeUserAvatar(@RequestParam("file") MultipartFile file,@RequestParam("userId")String userId) throws Exception {
        if (file.isEmpty()) {
            return Result.fail("上传失败，请选择文件","");
        }
        System.out.println("上传用户的用户id为："+userId);
        String fileName = file.getOriginalFilename();
        System.out.println("当前时间"+System.currentTimeMillis());

        File temp = MultipartFileToFile.multipartFileToFile(file);
       int responseCode =  UpAvatarUtils.up(temp,fileName);
       //然后删除本地头像
        MultipartFileToFile.delteTempFile(temp);
       String avatarUrl = "";
       if(responseCode==200)
       {
           avatarUrl="https://img.flya.top/avatar/"+fileName;
           //然后上传到数据库
           flUserMapper.updateAvatarByUserId(userId,avatarUrl);
           return Result.succ("上传成功",avatarUrl);
       }

        return Result.fail("上传失败","");
    }


    @GetMapping("/selectUserById")
    @ApiOperation(value = "通过用户名获取用户信息",notes = "传入用户id")
    Result getUserById(@RequestParam("userId")String userId)
    {
        FlUser flUser = flUserMapper.selectUserById(userId);
        if(flUser!=null)
        {
            return Result.succ("获取用户信息成功",flUser);
        }
        return Result.fail("获取用户信息失败","");
    }


}
